package maquinavotar.dao;

import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import java.io.File;
import org.w3c.dom.Document;
import maquinavotar.dto.CandidateDTO;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class CandidatesDAOImplXml implements CandidatesDAO {

    public List<CandidateDTO> loadCandidatos(String path) {
        List<CandidateDTO> cands = new ArrayList<CandidateDTO>();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc  = builder.parse(new File(path));

            NodeList listCands = doc.getElementsByTagName("candidato");
            for(int i = 0; i < listCands.getLength(); i ++) {
                Node candNode = listCands.item(i);

                Element elemento = (Element) candNode;
                CandidateDTO cand = new CandidateDTO( getTagValue("nombre",elemento),
                                                getTagValue("puesto",elemento),
                                                getTagValue("img",elemento) );
                cands.add(cand);
            }
        } catch(Exception e) {
            return null;
        }
        return cands;
    }
    
    private String getTagValue(String tag, Element elemento) {
        NodeList lista = elemento.getElementsByTagName(tag).item(0).getChildNodes();
        Node valor = (Node) lista.item(0);
        return valor.getNodeValue();
    }

}
